package com.example.emqx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.emqx.entity.ApiResponse;
import com.example.emqx.entity.DevicesEmqStatus;
import com.example.emqx.pojo.SendMessageRequest;
import com.example.emqx.service.DevicesEmqStatusService;
import com.example.emqx.service.NacosFeignClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;

//@RestController//用这个显示不出网页
@Slf4j
@RestController
public class SendController {

    @Autowired
    private DevicesEmqStatusService statusService;
    @Resource
    private ObjectMapper objectMapper;
    @Autowired
    private ExampleFeignService exampleFeignService;
    @Autowired
    private NacosFeignClient nacosFeignClient;

    //http://localhost:9000/devices?page=1&size=10
    @GetMapping("/devices")
    public ApiResponse<Page<DevicesEmqStatus>> getAllStatus(@RequestParam(value = "page", defaultValue = "1") int page,
                                               @RequestParam(value = "size", defaultValue = "10") int size) {
        // 使用 MyBatis-Plus 的 Page 类进行分页查询
        Page<DevicesEmqStatus> devicesEmqStatusPage = new Page<>(page, size);
        statusService.page(devicesEmqStatusPage, new QueryWrapper<DevicesEmqStatus>());
        return ApiResponse.success(devicesEmqStatusPage);
    }

    //http://localhost:9000/sendmsg?clientId=1&topic=1&message=1
    @GetMapping("/sendmsg")
    public ApiResponse<String> sendMessage(SendMessageRequest request) throws JsonProcessingException {
        log.info("sendMessage request:{}", objectMapper.writeValueAsString(request));
        // 处理发送消息的逻辑
        // 示例：
        // kafkaService.sendMessage(clientId, topic, message);

//        model.addAttribute("clientId", clientId);
//        model.addAttribute("topic", topic);
//        model.addAttribute("message", message);
        return exampleFeignService.sendMessage(request.getTopic() + "/" + request.getClientId(),
                request.getMessage());
    }
    //http://localhost:9000/nacosSendMessage?clientId=1&topic=1&message=1
    @GetMapping("/nacosSendMessage")
    public ApiResponse<String>  nacosSendMessage(SendMessageRequest request) throws JsonProcessingException {
        log.info("nacosSendMessage request:{}", objectMapper.writeValueAsString(request));
        // 处理发送消息的逻辑
        return nacosFeignClient.sendMessage(request.getTopic() + "/" + request.getClientId(),
                request.getMessage());
    }
}
